package com.acme.entity.security;

import java.security.SecureRandom;

import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKeyFactory;

import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class AppSecurity {
	
	//member variables
	private static final int CODE_BIT_SIZE = 130;
	private static final int SALT_BYTE_SIZE = 8;
	private static final int HASH_BYTE_SIZE = 24;
	private static final int PBKDF2_ITERATIONS = 1000;
	
	private static final int SALT_INDEX = 0;
	private static final int PBKDF2_INDEX = 1;
	
	private static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA1";
	
	//functions
	//creates the username and password passed in to store in the database
	//returns the user hash + salt and the password hash + salt.
	public static String[] createUser(String username, String password) 
	throws NoSuchAlgorithmException, InvalidKeySpecException {
		String [] userPassHash = new String[2];
		userPassHash[0] = createHash(username);
		userPassHash[1] = createHash(password);
		//String userHash = createUserHash(username);
		//String passHash = createPasswordHash(password);
		
		return userPassHash;
		//return userHash + "|" + passHash;
	}
	
	//creates a username to store in the database
	public static String createHash(String in)
	throws NoSuchAlgorithmException, InvalidKeySpecException {
		SecureRandom random = new SecureRandom();
		byte[] salt = new byte[SALT_BYTE_SIZE];
		random.nextBytes(salt);
		
		byte[] hash = pbkdf2(in.toCharArray(), salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
		
		
		return toHex(salt) + ":" + toHex(hash);
	}
	
	//checks if the hash passed in matches the stored hash for the user
	public static boolean validateHash(String input, String correctHash) 
	throws NoSuchAlgorithmException, InvalidKeySpecException {
		String[] params = correctHash.split(":");
		byte[] salt;
		byte[] hash;
		try {
			salt = fromHex(params[SALT_INDEX]);
			hash = fromHex(params[PBKDF2_INDEX]);
		}
		catch(ArrayIndexOutOfBoundsException e) {
			return false;
		}
		
		byte[] test = pbkdf2(input.toCharArray(), salt, PBKDF2_ITERATIONS, hash.length);
		
		return slowEquals(hash, test);
	}
	
	//returns a generated hash composed from the 'in' char[] and the salt
	private static byte[] pbkdf2(char[] in, byte[] salt, int iterations, int bytes)
	throws NoSuchAlgorithmException, InvalidKeySpecException {
		PBEKeySpec spec = new PBEKeySpec(in, salt, iterations, bytes * 8);
		SecretKeyFactory skf = SecretKeyFactory.getInstance(HASH_ALGORITHM);
		return skf.generateSecret(spec).getEncoded();
	}
	
	//returns values from byte[] converted to a hex string
	private static String toHex(byte[] array) {
		BigInteger bi = new BigInteger(1, array);
		String hex = bi.toString(16);
		int paddingLength = (array.length * 2) - hex.length();
		if(paddingLength > 0) {
			return String.format("%0" + paddingLength + "d", 0) + hex;
		}
		else {
			return hex;
		}
	}
	
	//returns a byte array with values converted from hex
	private static byte[] fromHex(String hex) {
		byte[] binary = new byte[hex.length() / 2];
		System.out.println("Contents of hex: " + hex);
		for(int i = 0; i < binary.length; ++i) {
			String hexByte = hex.substring(2*i, 2*i+2);
			System.out.println(hexByte);
			try{
				binary[i] = (byte)Integer.parseInt(hexByte, 16);
			}
			catch(NumberFormatException e){
				return binary;
			}
		}
		return binary;
	}
	
	//compares the bytes in the two arrays and returns whether they match or not
	private static boolean slowEquals(byte[] a, byte[] b) {
		int diff = a.length ^ b.length;
		for(int i = 0; i < a.length && i < b.length; ++i) {
			diff |= a[i] ^ b[i];
		}
		
		if(diff == 0){
			System.out.println("Hash match!");
		}
		else{
			System.out.println("Hash doesn't match :(");
		}
		
		return diff == 0;
	}
	
	public static String generateResetCode(){
		SecureRandom rand = new SecureRandom();
		
		String rCode = new BigInteger(CODE_BIT_SIZE, rand).toString(32);

		rCode = (String) rCode.subSequence(0, 6);
		//System.out.println(rCode);
		
		return rCode.toUpperCase();
	}
}